package servlet;
import entity.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    private Map<Integer,User> list = new HashMap<>();
    public UserServlet(){
        list.put(1,new User(1,"张三",65.5));
        list.put(2,new User(2,"李四",78.5));
        list.put(3,new User(3,"王二",99.5));
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method == null){
            method = "display";
        }
        switch (method){
            case "delete":
                Integer id = Integer.parseInt(req.getParameter("id"));
                list.remove(id);
                resp.sendRedirect("/user");// 这里没有传参，默认来到display里面
                break;
            case "display":
                req.setAttribute("list",list.values());
                req.getRequestDispatcher("index.jsp").forward(req,resp);
                break;
            case "replace":
                id = Integer.parseInt(req.getParameter("id"));
                User user = list.get(id);
                req.setAttribute("user",user);
                req.getRequestDispatcher("replace.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String idStr = req.getParameter("id");
        String nameStr = req.getParameter("name");
        String scoreStr = req.getParameter("score");
        Integer id = Integer.parseInt(idStr);
        String name = nameStr;
        Double score = Double.parseDouble(scoreStr);
        User user = new User(id, name, score);

        String method = req.getParameter("method");
        if(method == null){
            method = "save";
        }
        switch (method){
            case "save":
                list.put(id,user);
                resp.sendRedirect("/user");
                break;
            case "replace":
                list.put(id,user);
                resp.sendRedirect("/user");
                break;
        }
    }
}
